package com.simplenix.nicasio.misc;

import com.simplenix.nicasio.sys.SystemDef;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 *
 * @author fronald
 */
public class PropertiesReader {

	private Properties properties = new Properties();

	public PropertiesReader(File f) throws FileNotFoundException, IOException {
		this.properties.load(new FileInputStream(f));
	}

	/**
	 * If the resource is com.test.prop.properties, use com/test/prop.properties
	 * @param resourceName
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 */
	public PropertiesReader(String resourceName) throws FileNotFoundException, IOException {
		File f = new File(SystemDef.getInstance().getAppPath() + "/" + resourceName);
		FileInputStream fi = new FileInputStream(f);
		this.properties.load(fi);
	}

	public Map<String, String> getPropertiesAsMap() {
		Map<String, String> rtn = new HashMap<String, String>();
		for (String key : this.properties.stringPropertyNames()) {
			rtn.put(key, this.properties.getProperty(key));
		}
		return rtn;
	}

	public String getProperty(String key) {
		if (this.haveKey(key)) {
			return this.properties.getProperty(key);
		} else {
			return key;
		}
	}

	public void setProperty(String key, String value) {
		this.properties.setProperty(key, value);
	}

	public List<String> getKeys() {
		List<String> rtn = new ArrayList<String>();
		for (String key : this.properties.stringPropertyNames()) {
			rtn.add(key);
		}
		return rtn;
	}

	public boolean haveKey(String key) {
		return this.properties.containsKey(key);
	}

	public void saveToFile(String path) throws IOException {
		this.saveToFile(new File(path));
	}

	public void saveToFile(File file) throws IOException {
		this.properties.store(new FileOutputStream(file), null);
	}

}
